package com.aaa.sys.service.impl;

import com.aaa.common.util.ConstantUtil;
import com.aaa.common.util.OssUtil;
import com.aaa.sys.service.CommonFileHandlerService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ fileName:CommonFileHandlerServiceImpl
 * @ description:
 * @ author:xjd
 * @ createTime:2023/6/25 19:28
 * @ version:1.0.0
 */
@Service
public class CommonFileHandlerServiceImpl implements CommonFileHandlerService {
    @Override
    public Map uploadFile(MultipartFile multipartFile, String savePath) {

        InputStream inputStream = null;
        try {
            //根据文件对象获取流
            inputStream = multipartFile.getInputStream();
            //获取源文件名称
            String originalFilename = multipartFile.getOriginalFilename();
            //根据源文件名称获取后缀
            String suffix  =  originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼装新文件名称
            String newFileName = UUID.randomUUID().toString()+suffix;
            //拼装文件路径
            savePath = savePath+newFileName;
            //调用封装类 上传
            OssUtil.uploadFile(inputStream,savePath);
            //定义返回对象
            Map resultMap = new HashMap();
            //放入原始文件名称
            resultMap.put("fileOriginName",originalFilename);
            //ConstantUtil.FileHandlerConfig.BUCKET_DAEMON = https://qy164-wangzherongyao-bucket.oss-cn-beijing.aliyuncs.com/
            //savePath =  dept/a/b/c/ba0dea4a-93ac-484f-8a88-0444581100ef.txt
            // https://qy164-wangzherongyao-bucket.oss-cn-beijing.aliyuncs.com/dept/a/b/c/ba0dea4a-93ac-484f-8a88-0444581100ef.txt
            resultMap.put("avatar", ConstantUtil.FileHandlerConfig.BUCKET_DAEMON+savePath);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
